<template>
  <div class="app-container">
    <!-- 查询行 -->
    <el-row :gutter="10" class="mb8 query-row">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="queryParams.jobName" placeholder="请输入任务名称" clearable size="mini" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="queryParams.jobGroup" placeholder="请输入任务组名称" clearable size="mini" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="执行状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择执行状态" clearable size="mini" style="width: 240px" @change="$forceUpdate()">
            <el-option v-for="option in statusOptions" :key="option.dictValue" :label="option.dictLabel" :value="option.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务ID" prop="jobId" v-show="showSearch">
          <el-input v-model="queryParams.jobId" placeholder="请输入任务ID" clearable size="mini" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="执行时间" v-show="showSearch">
          <el-date-picker v-model="dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-hasPermi="['monitor:job:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" :loading="exportLoading" @click="handleAITLog">
          <svg-icon icon-class="log" /> 接口方法日志({{ currentRow && currentRow.jobLogId }})
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" :loading="exportLoading" @click="handleEntityInfo">
          <svg-icon icon-class="log" /> 接口实体日志({{ currentRow && currentRow.jobLogId }})
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" :loading="exportLoading" @click="handleFlowInfo">
          <svg-icon icon-class="documentation" /> 查看流程配置({{ currentRow && currentRow.jobLogId }})
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="mainTable" v-loading="loading" :data="jobLogList" @selection-change="handleSelectionChange"
      @current-change="handleCurrentChange" @row-dblclick="handleView" :row-style="{ height: '32px' }"
      :cell-style="{ padding: '0px' }" highlight-current-row border :height="tableHeight"
      :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志编号" width="80" align="center" prop="jobLogId" />
      <el-table-column label="任务ID" width="80" align="center" prop="jobId" :show-overflow-tooltip="true" />
      <el-table-column label="任务名称" width="120" align="center" prop="jobName" :show-overflow-tooltip="true" />
      <el-table-column label="任务组名" width="120" align="center" prop="jobGroup" :show-overflow-tooltip="true" />
      <el-table-column label="日志信息" width="300" align="center" prop="jobMessage" :show-overflow-tooltip="true" />
      <el-table-column label="执行状态" width="80" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="执行时间" width="180" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程ID" width="180" align="center" prop="flowId" />
      <el-table-column label="流程编码" width="200" align="center" prop="flowCode" :show-overflow-tooltip="true" />
      <el-table-column label="流程名称" width="180" align="center" prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="耗时(毫秒)" width="100" align="center" prop="runTime" />
      <el-table-column label="总记录数" width="100" align="center" prop="totalCnt" />
      <el-table-column label="成功条数" width="120" align="center" prop="successCnt" />
      <el-table-column label="失败条数" width="120" align="center" prop="errorCnt" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['monitor:job:query']">详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 调度日志详细 -->
    <el-dialog title="调度日志详细" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本" name="base">
            <el-row>
              <el-col :span="12">
                <el-form-item label="日志序号：">{{ form.jobLogId }}</el-form-item>
                <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
                <el-form-item label="执行时间：">{{ form.createTime }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="日志信息：">
                  <el-input type="textarea" :rows="10" v-model="form.jobMessage"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="执行状态：">
                  <div v-if="form.status == 0">正常</div>
                  <div v-else-if="form.status == 1">失败</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="异常信息：" v-if="form.status == 1">{{ form.exceptionInfo }}</el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="流程信息" name="flowInfo">
            <el-col :span="12">
              <el-form-item label="流程ID">{{ form.flowId }}</el-form-item>
              <el-form-item label="流程编码">{{ form.flowCode }}</el-form-item>
              <el-form-item label="流程名称">{{ form.flowName }}</el-form-item>
              <el-form-item label="总记录数">{{ form.totalCnt }}</el-form-item>
              <el-form-item label="成功条数">{{ form.successCnt }}</el-form-item>
              <el-form-item label="失败条数">{{ form.errorCnt }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间">{{ form.startDate }}</el-form-item>
              <el-form-item label="开始时间">{{ form.endDate }}</el-form-item>
              <el-form-item label="耗时(毫秒)">{{ form.runTime }}</el-form-item>
            </el-col>
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <flow-info-dlg :visible.sync="flowOpen" :code="currentRow && currentRow.flowCode"></flow-info-dlg>

  </div>
</template>

<script>
import { listJobLog, delJobLog, exportJobLog, cleanJobLog } from "@/api/monitor/jobLog";
import FlowInfoDlg from '@/components/AIT/FlowInfo';

export default {
  name: "JobLog",
  components: { FlowInfoDlg },
  data() {
    return {
      // 流程详情
      flowOpen: false,
      // 当前行
      currentRow: null,
      //表格高度
      tableHeight: 500,
      // 默认页签
      activeName: 'base',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 调度日志表格数据
      jobLogList: [],
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 执行状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_job_log_status").then(response => {
      this.statusOptions = response.data;
      console.info('statusOptions:',this.statusOptions)
    });
  },
  mounted() {
    this.$nextTick(() => {
      // window.innerHeight 浏览器窗口的可见高度，下面的 220 是除了table最大高度的剩余空间。
      let height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 220;
      this.tableHeight = height;
    });
    // console.info('mounted',this.$route.query);
  },
  watch: {
    "$route"(to,from){
        // console.info('watch to',to,'from',from)
        if (to.path === '/ait/log') {
          this.getList();
      }
    }
  },
  methods: {
    handleCurrentChange(val) {
      // console.info('handleCurrentChange',val)
      this.currentRow = val;
      val && this.$refs.mainTable.toggleRowSelection(val);
    },
    /** 查询调度日志列表 */
    getList() {
      this.loading = true;
      // 通过路由构造查询
      if (!this.queryParams.jobId && this.$route.query.jobId)
        this.queryParams.jobId = this.$route.query.jobId;
      if (!this.queryParams.status && this.$route.query.status)
        this.queryParams.status=this.$route.query.status;
      if ((this.dateRange==undefined||this.dateRange.length==0) && this.$route.query.beginTime)
        this.dateRange = [this.$route.query.beginTime, this.$route.query.endTime];
      
      // 调用查询服务
      let query=this.addDateRange(this.queryParams, this.dateRange)
      // console.info('queryParams,dateRange,query',this.queryParams, this.dateRange,query)
      listJobLog(query).then(response => {
        this.jobLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },
    // 执行状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 20
      };
      this.dateRange = [];
      this.resetForm("queryForm");

      // 判断路由是否为空
      if (Object.keys(this.$route.query).length == 0)
        // 如果路由为空,直接查询
        this.handleQuery();
      else
        // 如果路由不空,清除路由
        this.$router.push({ query: {} })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobLogId);
      this.multiple = !selection.length;
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    handleFlowInfo() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      // console.info('handleFlowInfo',this.currentRow)
      this.flowOpen = true;
    },
    handleEntityInfo() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      // 跳转指定页面,带入查询参数
      this.$router.push({
        path: "/ait/EntityInfo",
        query: {
          flowId: this.currentRow.flowId
        }
      });
    },
    handleAITLog() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择一条记录!',
          type: 'warning'
        });
        return;
      }
      // 跳转指定页面,带入查询参数
      this.$router.push({
        path: "/ait/aitlog",
        query: {
          flowId: this.currentRow.flowId
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有调度日志数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportJobLog(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.status === '0') {
        return 'normal-row';
      } else {
        return 'abnormal-row';
      }
    }
  }
};
</script>
